package com.zhushu.projectscheduling;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.concurrent.Task;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.stage.Stage;
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.HttpEntity;
import org.apache.hc.core5.http.io.entity.EntityUtils;

import java.time.LocalDate;


public class HelloApplication extends Application {
    @Override
    public void start(Stage stage) throws Exception {
        FXMLLoader fxmlLoader = new FXMLLoader(HelloApplication.class.getResource("hello-view.fxml"));
        Scene scene = new Scene(fxmlLoader.load(), 800, 600);


        HelloController  controller = fxmlLoader.getController();
        controller.setMsgLabelMsg("正在同步本年度节假日信息，请稍等...", 0);

        // 创建一个后台任务
        Task<Void> backgroundTask = new Task<Void>() {
            @Override
            protected Void call() throws Exception {
                // 同步节假日信息
                fetchData(controller);
                return null;
            }
        };

        // 启动后台任务
        new Thread(backgroundTask).start();

        stage.setTitle("资源排期工具（author：zhushu）");
        stage.getIcons().add(new Image("img/icon.png"));
        stage.setScene(scene);
        stage.show();

    }

    /**
     * 更改页面提示信息
     * @param controller
     * @param msg
     * @throws Exception
     */
    private void changeMsg(HelloController  controller, String msg, int state){
        Platform.runLater(() -> {
            controller.setMsgLabelMsg(msg, state);
        });
    }

    /**
     * 通过接口获取节假日信息
     * @param controller
     */
    private void fetchData(HelloController  controller){
        // 获取当前时间的年份
        LocalDate localDate = LocalDate.now();
        String url = "https://date.appworlds.cn/year/"+localDate.getYear();
        int state = 0;
        String msg;
        String resultJson = null;

        HttpGet httpGet = new HttpGet(url);
        try {
            CloseableHttpClient httpclient = HttpClients.createDefault();
            CloseableHttpResponse response = httpclient.execute(httpGet);
            HttpEntity entity = response.getEntity();
            // 获取响应信息
            resultJson = EntityUtils.toString(entity);
            fillDayList(controller, resultJson);
            msg = "节假日信息获取成功";
            state = 1;
        } catch (Exception e) {
            e.printStackTrace();
            msg = "节假日信息获取失败:"+e.getMessage();
            state = 0;
        }

        changeMsg(controller, msg, state);

    }

    /**
     * 组装信息返回页面
     * @param controller
     * @param resultJson
     */
    private void fillDayList(HelloController  controller, String resultJson){
        JSONObject jsonObject = JSONObject.parseObject(resultJson);
        JSONArray dateArray = jsonObject.getJSONArray("data");

        String workdayText = "";
        String holidayText = "";

        for (int i = 0; i < dateArray.size(); i++) {
            JSONObject obj = dateArray.getJSONObject(i);

            boolean isHoliday = obj.getBoolean("holiday");
            String dateStr = obj.getString("date");
            if(isHoliday){
                holidayText += dateStr + "\n";
            }else{
                workdayText += dateStr + "\n";
            }

        }
        controller.setWorkdayTextArea(workdayText);
        controller.setHolidayTextArea(holidayText);

    }


    public static void main(String[] args) {
        launch();
    }
}